using UnityEngine;
using System.Collections;
using System;
using System.Configuration;
using System.Collections.Generic;
using System.Text;


public class ChatNetHandler : Singleton< ChatNetHandler > 
{
	
	void Awake ()
	{
		if ( mInstance == null )
		{
			mInstance = this;
			initHandler();
		}
		
	}
	
	public void initHandler()
	{
		GameSocketManager.instance.regeditMsg( (int)GameNetMessage.MsgType._MSG_RECV_CHAT_MSG , recvChatMsg , typeof( GameNetMessage.SEND_RECV_MSG_CHAT_MSG ) );
				
	}

	public unsafe void sendChatMsg( string chat )
	{
		GameNetMessage.SEND_RECV_MSG_CHAT_MSG msg = new GameNetMessage.SEND_RECV_MSG_CHAT_MSG();
		msg.initNetHead();

		fixed( byte* pb = GamePlayerData.instance.creatureData.Name )
		{
			for ( int i = 0 ; i < GameDefine.MAX_NAME ; i++ ) 
			{
				msg.Name[ i ] = pb[ i ];
			}
		}

		byte[] b = Encoding.Unicode.GetBytes( chat );
		if ( b.Length >= GameDefine.MAX_CHAT_MSG )
		{
			b[ GameDefine.MAX_CHAT_MSG - 2 ] = 0;
			b[ GameDefine.MAX_CHAT_MSG - 1 ] = 0;
		}

		for ( int i = 0 ; i < b.Length ; i++ ) 
		{
			msg.Chat[ i ] = b[ i ];
		}

		GameSocketManager.instance.sendMsg( msg );
	}

	
	public unsafe void recvChatMsg( GameNetMessage.NetMsgInterface head )
	{
		GameNetMessage.SEND_RECV_MSG_CHAT_MSG msg = ( GameNetMessage.SEND_RECV_MSG_CHAT_MSG )head;

		byte[] name = new byte[ GameDefine.MAX_NAME ];
		byte[] chat = new byte[ GameDefine.MAX_CHAT_MSG ];

		for ( int i = 0 ; i < GameDefine.MAX_NAME ; i++ ) 
		{
			name[ i ] = msg.Name[ i ];
		}

		for ( int i = 0 ; i < GameDefine.MAX_CHAT_MSG ; i++ ) 
		{
			chat[ i ] = msg.Chat[ i ];
		}

		byte[] unicodeBytes = Encoding.Convert( Encoding.UTF8 , Encoding.Unicode , name );

		string name1 = Encoding.Unicode.GetString( unicodeBytes ).TrimEnd( '\0' );
		string chat1 = Encoding.Unicode.GetString( chat ).TrimEnd( '\0' );

		ChatUIHandler.instance.addChat( name1 , chat1 );
	}
	
	
}


